package oss

import (
	"gitee.com/xlizy/common-go/utils/zlog"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"net/url"
	"strings"
)

type RootConfig struct {
	Config ossConfig `yaml:"oss"`
}

type ossConfig struct {
	Endpoint          string `yaml:"endpoint"`
	AccessKeyId       string `yaml:"accessKeyId"`
	AccessKeySecret   string `yaml:"accessKeySecret"`
	DefaultBucketName string `yaml:"defaultBucketName"`
}

var _defaultBucketName = ""

var _client *oss.Client

func NewConfig() *RootConfig {
	return &RootConfig{}
}

func InitOSS(rc *RootConfig) {
	cfg := rc.Config
	_defaultBucketName = cfg.DefaultBucketName
	c, err := oss.New(cfg.Endpoint, cfg.AccessKeyId, cfg.AccessKeySecret)
	if err != nil {
		zlog.Error("初始化OSS异常:{}", err.Error())
		panic(err)
	}
	_client = c
}

func UploadForFile(key string, reader io.Reader, bucketName string) bool {
	if bucketName == "" {
		bucketName = _defaultBucketName
	}
	bucket, err := _client.Bucket(bucketName)
	if err != nil {
		zlog.Error("初始化OSS-bucket异常", err)
		return false
	}
	err2 := bucket.PutObject(key, reader)
	if err2 != nil {
		zlog.Error("上传文件异常", err2)
		return false
	}
	return true
}

func DeleteOSSFile(key, bucketName string) bool {
	if bucketName == "" {
		bucketName = _defaultBucketName
	}
	bucket, err := _client.Bucket(bucketName)
	if err != nil {
		zlog.Error("初始化OSS-bucket异常", err)
		return false
	}
	err2 := bucket.DeleteObject(key)
	if err2 != nil {
		zlog.Error("删除文件异常", err2)
		return false
	}
	return true
}

func MoveOSSFile(srcKey, destKey, bucketName string) bool {
	if srcKey == destKey {
		return true
	}
	if bucketName == "" {
		bucketName = _defaultBucketName
	}
	bucket, err := _client.Bucket(bucketName)
	if err != nil {
		zlog.Error("初始化OSS-bucket异常", err)
		return false
	}
	if strings.HasPrefix(srcKey, "/") {
		srcKey = srcKey[1:]
	}
	if strings.HasPrefix(destKey, "/") {
		destKey = destKey[1:]
	}
	_, err2 := bucket.CopyObject(srcKey, destKey)
	if err2 != nil {
		zlog.Error("拷贝文件异常", err2)
		return false
	} else {
		_ = bucket.DeleteObject(srcKey)
	}
	return true
}

func SignURL(objectName, bucketName, fileName string) (string, error) {
	if bucketName == "" {
		bucketName = _defaultBucketName
	}
	bucket, err1 := _client.Bucket(bucketName)
	if err1 != nil {
		zlog.Error("初始化OSS-bucket异常", err1)
		return "", err1
	}
	opts := make([]oss.Option, 0)
	if fileName != "" {
		opts = append(opts, oss.AddParam("response-content-disposition", "attachment;filename="+url.QueryEscape(fileName)))
	}
	signedURL, err2 := bucket.SignURL(objectName, oss.HTTPGet, 600, opts...)
	if err2 != nil {
		zlog.Error("生成签名Url异常", err2)
		return "", err2
	} else {
		return signedURL, nil
	}
}
